using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using LitJson;
using System.Xml;

namespace xingzhimeng
{
    public class Game : MonoBehaviour
    {
        public GameObject Muen;
        public Toggle toggle;
        private AudioSource source;
        public GameObject showPlane;
        
        private void Awake()
        {
            Pause();
            source = toggle.GetComponent<AudioSource>();
            toggle.isOn=Boolean.Parse(PlayerPrefs.GetString("Source","true"));
            KongzhiSoure();
        }

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.Escape))
            {
                Pause();
            }
        }

        IEnumerator ShowPlane(string name)
        {
            showPlane.SetActive(true);
            showPlane.GetComponent<Text>().text = name;
            yield return new WaitForSeconds(1);
            showPlane.SetActive(false);
        }

        //暂停方法
        public void Pause()
        {
            Time.timeScale = 0;
            Muen.SetActive((true));
            Cursor.visible = true;
        }

        //继续游戏
        public void UnPause()
        {
            Time.timeScale = 1;
            Muen.SetActive((false));
            Cursor.visible = false;
        }
       //新游戏
        public void NewGame()
        {
            ShootScoreManager.insernt.score.text = "0";
            ShootScoreManager.insernt.shoot.text = "0";
            UnPause();
            EnemyManager.insernt.UpGame();
        }
        //退出游戏
        public void Quit()
        {
            
            #if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
            #else
            Application.Quit();
            #endif
            
        }
        //控制音量
        public void KongzhiSoure()
        {
            source.enabled = toggle.isOn;
            PlayerPrefs.SetString("Source",toggle.isOn.ToString());
        }
       //保存游戏
        public void SaveGame()
        {
            //saveBin();
            //saveJson();
            saveXml();
        }
        //加载游戏

        public void LoadGame()
        {
          // loadBin(); 
          //loadJson();
          loadXml();
        }
//以二级制的方式保存数据
        private void saveBin()
        {//Save类一定要标明[System.Serializable]可序列化
            string patch = Application.dataPath + "/StreamingFile" + "/data.txt";
            Save save = EnemyManager.insernt.GetSaveData();//
            BinaryFormatter bf = new BinaryFormatter();//序列化对象
            FileStream stream = new FileStream(patch,    FileMode.OpenOrCreate);//创建流
            bf.Serialize(stream,save);//写入文件
            stream.Close();
            if(File.Exists(patch))
               StartCoroutine( ShowPlane("保存成功"));
            else
            {
              StartCoroutine(  ShowPlane("保存失败"));
            }
            
        }
//以二级制的方式读取数据
        private void loadBin()
        {
            string patch = Application.dataPath + "/StreamingFile" + "/data.txt";
            if (File.Exists(patch))
            {
                BinaryFormatter bf = new BinaryFormatter();
                FileStream stream = File.Open(patch, FileMode.Open);
                Save save = bf.Deserialize(stream) as Save;//读取对象
                stream.Close(); 
                EnemyManager.insernt.ActiveEnemyByType(save);
                UnPause();
            }
            else
            {
                StartCoroutine(ShowPlane("加载失败"));
            }



        }

        private void saveXml()
        {
            string path=Application.dataPath + "/StreamingFile" + "/data2.txt";
            Save save = EnemyManager.insernt.GetSaveData();
            XmlDocument document = new XmlDocument();
            XmlElement root = document.CreateElement("GameData");
            XmlElement target;
            XmlElement EnemtPoint;
            XmlElement EnemtType;
            for(int i=0;i<save.EnemyPoint.Count;i++)
            {
                target = document.CreateElement("target");
                EnemtPoint = document.CreateElement("EnemtPoint");
                EnemtPoint.InnerText = save.EnemyPoint[i].ToString();
                EnemtType = document.CreateElement("EnemtType");
                EnemtType.InnerText = save.Enemytype[i].ToString();
                target.AppendChild(EnemtPoint);
                target.AppendChild(EnemtType);
                root.AppendChild(target);

            }

            XmlElement ShootNum = document.CreateElement("ShootNum");
            ShootNum.InnerText = save.shootNum;
            XmlElement Score = document.CreateElement("Score");
            Score.InnerText = save.score;
            root.AppendChild(ShootNum);
            root.AppendChild(Score);
            document.AppendChild(root);
            document.Save(path);
            if (File.Exists(path))
            {
                StartCoroutine(ShowPlane("保存成功"));
            }
            else
            {
                StartCoroutine(ShowPlane("保存失败"));
            }






        }

        private void loadXml()
        {
            string path=Application.dataPath + "/StreamingFile" + "/data2.txt";
            if (File.Exists(path))
            {
                Save save = new Save
                {
                    Enemytype = new List<int>(),
                    EnemyPoint = new List<int>()

                };
                    
                XmlDocument document = new XmlDocument();
                document.Load(path);
            XmlNodeList list=    document.GetElementsByTagName("target");
            foreach (XmlElement item in list)
            {
             int poiniId=int.Parse(item.ChildNodes[0].InnerText);
             int EnemeType = int.Parse(item.ChildNodes[1].InnerText);
             save.EnemyPoint.Add(poiniId);
             save.Enemytype.Add(EnemeType);

            }

            string shootNum = document.SelectSingleNode("GameData").SelectSingleNode("ShootNum").InnerText;
            string score = document.SelectSingleNode("GameData").SelectSingleNode("Score").InnerText;
            save.score = score;
            save.shootNum = shootNum;
            EnemyManager.insernt.ActiveEnemyByType(save);
            UnPause();

            //  StartCoroutine(ShowPlane("j"))
            }
            else
            {
                StartCoroutine(ShowPlane("加载失败"));
            }
            
        }
//以Json的方式保存数据
        private void saveJson()
        {
            string path=Application.dataPath + "/StreamingFile" + "/data1.json";
            Save save = EnemyManager.insernt.GetSaveData();
            StreamWriter writer = new StreamWriter(path);
            string json=  JsonMapper.ToJson(save);
            writer.Write(json); 
            writer.Close();
            if (File.Exists(path))
               StartCoroutine( ShowPlane("保存成功"));
            else
            {
               StartCoroutine( ShowPlane("保存失败"));
            }
            
        }

        private void loadJson()
        {
            string path=Application.dataPath + "/StreamingFile" + "/data1.json";
            if (File.Exists(path))
            {
                StreamReader reader = new StreamReader(path);
                string data = reader.ReadToEnd();
                reader.Close();
                Save save = JsonMapper.ToObject<Save>(data);
                EnemyManager.insernt.ActiveEnemyByType(save);
                UnPause();
                

            }
            else
            {
                StartCoroutine(ShowPlane("加载失败"));
            }
        }
    }
}